// 排行榜(每小时更新前100)
let mongoose = require('mongoose');
const Cron = require('node-cron');

let rankingList = [];

let updateRankingList = async function(){
    rankingList = [];
    let time = Date.now();
    let GameUserModel = mongoose.models['GameUser'];
    let minTime = Date.now() - 30 * 24 * 60 * 60 * 1000;
    let gameUsers = await GameUserModel.find({lastLoginTick: {$gte: minTime}}).sort({level: -1}).limit(100);
    for(let i = 0 ; i < gameUsers.length ; i++){
        if(!gameUsers[i].nickname || !gameUsers[i].headImgUrl) continue;
        rankingList.push({
            level: gameUsers[i].level,
            nickname: gameUsers[i].nickname,
            headImgUrl: gameUsers[i].headImgUrl,
            lastLoginTick: gameUsers[i].lastLoginTick,
            levelName: gameUsers[i].getLevelName({self: this}),
            openid: gameUsers[i].openid
        });
    }
    rankingList.sort( (a, b) => {
        return a.level == b.level ? b.lastLoginTick - a.lastLoginTick : b.level - a.level;
    });
    console.log('rankTime ==', Date.now() - time);
};

module.exports = {
    run(){
        Cron.schedule('0 1 * * * *', updateRankingList);

        setTimeout(() => {
            updateRankingList();
        }, 5000);
    },
    getRankList(options){
        let page = parseInt(options.page);
        let ranks = [...rankingList];
        return ranks.splice(page * 20, 20);
    },
};